import { delApp, editApp, getInfo, getList, getTree } from "@/api/modules/basic/api";
import DialogBox from "@/components/DialogBox";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { menuType } from "@/enums/dictEnum";
import { ResultEnum } from "@/enums/httpEnum";
import { useAuthButtonList } from "@/hooks/useAuthButtons";
import { copyToClipboard, deepClone, treeDataToList, unique } from "@/utils/util";
import { ElButton, ElCheckbox, ElInput, ElLink, ElMessage, ElMessageBox, ElTag } from "element-plus";
import { dayjs } from "element-plus";
import { getCurrentInstance, defineComponent, reactive, ref, ComponentInternalInstance } from "vue";
import Form from "./form";
import "./index.scss";
const API = defineComponent({
	components: {
		Form
	},
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const data = reactive({
			column: [
				{ type: "selection", width: 50 },
				{
					label: proxy?.$t("basic_api.tablist_label.appname"),
					prop: "appName",
					search: {
						el: "input",
						key: "search"
					}
				},
				{ label: proxy?.$t("basic_api.tablist_label.status"), prop: "status", width: 100 },
				{ label: proxy?.$t("basic_api.tablist_label.expiretime"), prop: "expireTime", width: 170 },
				{ label: proxy?.$t("basic_api.tablist_label.expiretype"), prop: "expireType", width: 100 },
				// { label: "创建时间", prop: "createTime" },
				{ label: proxy?.$t("basic_api.tablist_label.operation"), prop: "operation", width: 180, fixed: "right" }
			] as ColumnProps[],
			columnApi: [
				{ label: proxy?.$t("basic_api.tablist_label.mname"), prop: "MName", width: 120 },
				{ label: proxy?.$t("basic_api.tablist_label.classify"), prop: "CName", width: 180 },
				{ label: proxy?.$t("basic_api.tablist_label.address"), prop: "FName", align: "left" }
			] as ColumnProps[],
			btnList: [] as any,
			apiList: [] as any,
			ckList: [] as any,
			ckInfo: {} as any,
			showToken: false,
			tokenInfo: "",
			searchVal: "",
			spanShow: true
		});
		const refForm = ref();
		const proTable = ref();
		const tableRef = ref();
		// 获取按钮
		useAuthButtonList().then((res: any) => {
			data.btnList = res;
		});
		// 列表请求返回方法
		const dataCallback = (row: any) => {
			return {
				datalist: row.records,
				pageIndex: row.pages,
				pageSize: row.size,
				total: row.total
			};
		};
		// 按钮事件执行方法
		const handleFun = (fn: string | number, row?: any) => {
			switch (fn) {
				case "add": // 添加
					refForm.value.Init();
					break;
				case "del": // 批量删除
					if (row.selectList.length == 0) return ElMessage.error(proxy?.$t("basic_api.elmsg.del"));
					ElMessageBox.confirm(proxy?.$t("basic_api.elmsg_confirm.del"), proxy?.$t("basic_api.elmsg.tip"), {
						type: "warning"
					}).then(() => {
						Del(row.selectList.map((el: any) => el.appId).join(","));
					});
					break;
				case "edit": // 修改
					refForm.value.Init(row);
					break;
				case "delOperation": // 单个删除
					ElMessageBox.confirm(proxy?.$t("basic_api.elmsg_confirm.del_operation"), proxy?.$t("basic_api.elmsg.tip"), {
						type: "warning"
					}).then(() => {
						Del(row.appId);
					});
					break;
				case "reset":
				case "search":
					data.ckInfo = {};
					data.ckList = [];
					break;
				case "allSlt": // 全选
					if (row) {
						data.ckList = [...data.apiList.map((e: any) => e.path), ...data.apiList.map((e: any) => e.CId)];
					} else {
						data.ckList = [];
					}
					data.ckList = unique(data.ckList);
					console.log(data.ckList);
					break;
				case "save": // 保存api权限
					// if (!data.ckList || data.ckList.length == 0) {
					// 	ElMessage.warning("请只选选择一项");
					// 	return
					// }
					editApp({
						appId: data.ckInfo.appId,
						apiList: unique(data.ckList).filter((e: any) => isNaN(e))
					}).then((res: any) => {
						if (res.code == ResultEnum.SUCCESS) {
							ElMessage.success(proxy?.$t("basic_api.elmsg.editsuccess"));
							// proTable.value?.searchEstend();
						} else {
							ElMessage.error(res.message || proxy?.$t("basic_api.elmsg.fail"));
						}
					});
					break;
				case "showToken": // 显示token
					data.showToken = true;
					data.tokenInfo = row.appToken;
					break;
				case "copy": // 复制
					copyToClipboard(data.tokenInfo);
					ElMessage.success(proxy?.$t("basic_api.elmsg.copysuccess"));
					break;
				case "filter":
					tableRef.value.getTableList();
					// const hf = {
					// 	text: data.searchVal,
					// 	dom: document.querySelector(".table-filter"),
					// 	index: data.filterIndex
					// };
					// htmlFilter(hf);
					// data.filterIndex = hf.index;
					// console.log(hf.index, data.filterIndex);
					break;
			}
		};
		// 删除应用
		const Del = (id: string) => {
			delApp(id).then((res: any) => {
				if (res.code == ResultEnum.SUCCESS) {
					ElMessage.success(proxy?.$t("basic_api.elmsg.delsuccess"));
					proTable.value?.getTableList();
					proTable.value?.clearSelection();
					data.ckInfo = {};
					data.ckList = [];
				} else {
					ElMessage.error(res.message || proxy?.$t("basic_api.elmsg.fail"));
				}
			});
		};
		// 获取api树
		const getApiTree = (res: any) => {
			if (!res || res.length == 0) return;
			const apiTreeData = res;
			let apiList = treeDataToList(apiTreeData);
			let deepInfo = [] as any;
			// 进行数据整合
			if (apiList && apiList.length) {
				apiList.forEach((e: any) => {
					let MName = "";
					let CName = "";
					let FName: string | undefined = "";
					let MId = "";
					let CId = "";
					let FId = "";
					let isDel = false;
					let CDisabled = false;
					let FDisabled = false;
					let selectAll = false;
					let path = "";
					if (e.parentId == "0") {
						MName = e.name;
						MId = e.id;
						isDel = true;
					} else {
						const pInfo = apiList.filter((el: any) => el.id == e.pid)[0];
						if (pInfo) {
							if (pInfo.parentId == "0") {
								MName = pInfo.name;
								MId = pInfo.id;
								if (e.path == "") {
									CName = e.name;
									CId = e.id;
									FName = proxy?.$t("basic_api.check_box.all");
									FId = e.id;
									selectAll = true;
									path = e.path;
									isDel = true;
								} else {
									CName = pInfo.name;
									CId = pInfo.id + 1;
									FName = e.name;
									FId = e.id;
									selectAll = true;
									path = e.path;
								}
							} else {
								const mInfo = apiList.filter((el: any) => el.id == pInfo.pid && el.pid == 0)[0] || {};
								MName = mInfo.name;
								MId = mInfo.id;
								CName = pInfo.name;
								CId = pInfo.id;
								FName = e.name;
								FId = e.id;
								path = e.path;
							}
							// CDisabled = this.isAdmin ? false : !list.includes(pInfo.id)
						}
						// if (
						// 	deepInfo.filter((ef: any) => ef.CId == pInfo.id && ef.selectAll).length == 0 &&
						// 	apiList.filter((ef: any) => ef.pid == pInfo.id).length > 1
						// ) {
						// 	selectAll = true;
						// }
						//   FDisabled = this.isAdmin ? false : !list.includes(e.id)
					}
					// if (selectAll) {
					// 	deepInfo.push({
					// 		id: e.id + "_1",
					// 		label: e.name,
					// 		MName: MName, // 目录名称
					// 		MId,
					// 		CName: CName, // 菜单名称
					// 		CId,
					// 		FName: "全选", // 按钮名称
					// 		FId: FId + "_1",
					// 		isDel, // 是否删除
					// 		CDisabled,
					// 		selectAll
					// 	});
					// }
					deepInfo.push({
						id: e.id,
						label: e.name,
						MName: MName, // 目录名称
						MId,
						CName: CName, // 菜单名称
						CId,
						FName: FName, // 按钮名称
						FId,
						isDel, // 是否删除
						CDisabled,
						FDisabled: CDisabled || FDisabled,
						selectAll,
						path: path
					});
				});
			}
			deepInfo = deepInfo.filter((e: any) => !e.isDel);
			// 添加全选
			const deepList = deepClone(deepInfo);
			let ckid = "";
			let index = 0;
			for (let i = 0; i < deepList.length; i++) {
				if (ckid != deepList[i].CId) {
					ckid = deepList[i].CId;
					const info = deepClone(deepList[i]);
					info.FName = proxy?.$t("basic_api.check_box.all");
					info.FId = info.CId;
					info.path = "";
					info.selectAll = true;
					deepInfo.splice(i + index, 0, info);
					index++;
				}
			}
			if (data.searchVal) {
				deepInfo = deepInfo.filter((el: any) => el.MName.indexOf(data.searchVal) >= 0 || el.path.indexOf(data.searchVal) >= 0);
				data.spanShow = false;
			} else {
				data.spanShow = true;
				// 进行数据结合
				let rowSpan = 0;
				let rowSpan1 = 0;
				// 计算合并项
				deepInfo.map((e: any) => {
					if (e.MId == rowSpan) {
						e.rowSpan = 0;
					} else {
						e.rowSpan = deepInfo.filter((el: any) => el.MId == e.MId).length;
						rowSpan = e.MId;
					}
					if (e.CId == rowSpan1) {
						e.rowSpan1 = 0;
					} else {
						e.rowSpan1 = deepInfo.filter((el: any) => el.CId == e.CId).length;
						rowSpan1 = e.CId;
					}
					// // 判断是否禁用全选
					// if (
					// 	e.selectAll &&
					// 	deepInfo.filter((el: any) => el.CId == e.CId && !el.selectAll).length ==
					// 		deepInfo.filter((el: any) => el.CId == e.CId && el.FDisabled && !el.selectAll).length
					// ) {
					// 	e.FDisabled = true;
					// }
					return e;
				});
			}
			console.log(deepInfo);
			data.apiList = deepInfo;
			return {
				datalist: deepInfo
			};
		};
		// checkbox变化 type 1 目录 2 分类 3 API地址
		const ckChange = (row: any, el: any, type?: number) => {
			if (row.selectAll) {
				if (el) {
					data.ckList.push(row.FId);
				} else {
					let index = data.ckList.indexOf(row.FId);
					data.ckList.splice(index, 1);
				}
				data.apiList.map((e: any) => {
					// if (e.MId == row.MId && e.rowSpan && !e.CDisabled && row.FVal) {
					//     data.apiList.push(row.MId)
					// }
					// if (e.CId == row.CId && e.rowSpan1 && !e.CDisabled) {
					//   data.apiList.push(row.CId)
					// }
					if (e.CId == row.CId) {
						if (el) {
							e.path ? data.ckList.push(e.path) : "";
						} else {
							let index = data.ckList.indexOf(e.path);
							data.ckList.splice(index, 1);
						}
					}
				});
			} else {
				data.apiList.map((e: any) => {
					if (type == 3) {
						if (e.FId == row.FId) {
							if (el) {
								e.path ? data.ckList.push(e.path) : "";
							} else {
								const index = data.ckList.indexOf(e.path);
								data.ckList.splice(index, 1);
							}
						}
					} else if (type == 2) {
						if (e.CId == row.CId) {
							if (el) {
								e.path ? data.ckList.push(e.path) : "";
								data.ckList.push(e.CId);
							} else {
								let index = data.ckList.indexOf(e.path);
								data.ckList.splice(index, 1);
								index = data.ckList.indexOf(e.CId);
								data.ckList.splice(index, 1);
							}
						}
					}
				});
			}
			data.ckList = unique(data.ckList);
			console.log(data.ckList);
		};
		// 表格点击
		const clickRow = (row: any) => {
			data.searchVal = "";
			data.ckInfo = row;
			tableRef.value.getTableList();
			getInfo(row.appId).then((res: any) => {
				data.ckList = res.result?.apiList || [];
				if (data.apiList.length) {
					data.apiList.map((el: any) => {
						if (el.rowSpan1 != 0) {
							const flt = data.apiList.filter((e: any) => e.CId == el.CId).map((e: any) => e.path);
							if (flt && flt.length) {
								let bl = true;
								flt.map((e: any) => {
									if (!data.ckList.includes(e) && bl && e) {
										bl = false;
									}
								});
								if (bl) {
									data.ckList.push(el.CId);
								}
							}
						}
					});
				}
			});
		};
		return () => {
			return h(
				<div class="table-box">
					<div class="flex h-full">
						<div class="flex-1 table-box">
							<ProTable
								ref={proTable}
								columns={data.column}
								requestApi={getList}
								dataCallback={dataCallback}
								onClickRow={clickRow}
								onReset={() => {
									handleFun("reset");
								}}
								onSearch={() => {
									handleFun("search");
								}}
							>
								{{
									tableHeader: (scoped: any) => {
										return data.btnList
											?.filter((el: any) => el.type == menuType.btn)
											.map((el: any) => {
												return h(
													<ElButton
														type={el.perms}
														onClick={(event: any) => {
															event.stopPropagation();
															handleFun(el.path, scoped);
														}}
													>
														{el.menuName}
													</ElButton>
												);
											});
									},
									operation: (scoped: any) => {
										return data.btnList
											?.filter((el: any) => el.type == menuType.operate)
											.map((el: any) => {
												return h(
													<ElLink
														type="primary"
														onClick={() => {
															handleFun(el.path, scoped.row);
														}}
													>
														{el.menuName}
													</ElLink>
												);
											});
									},
									status: (scoped: any) => {
										return h(
											<ElTag type={scoped.row.status == 1 ? "success" : "danger"}>
												{scoped.row.status == 1 ? proxy?.$t("basic_api.status.enable") : proxy?.$t("basic_api.status.disable")}
											</ElTag>
										);
									},
									expireType: (scoped: any) => {
										return h(
											<ElTag type={!dayjs(scoped.row.expireTime).isBefore(dayjs()) ? "success" : "danger"}>
												{!dayjs(scoped.row.expireTime).isBefore(dayjs())
													? proxy?.$t("basic_api.expire_type.effective")
													: proxy?.$t("basic_api.expire_type.expired")}
											</ElTag>
										);
									}
								}}
							</ProTable>
						</div>
						<div class="flex-1 ml-4 table-box">
							<div class="bg-white flex items-center justify-end px-3" style="height: 68px;margin-bottom: 5px;">
								{data.ckInfo.appName ? (
									<>
										<ElCheckbox
											class="mr-auto"
											onChange={(val: any) => {
												handleFun("allSlt", val);
											}}
										>
											{proxy?.$t("basic_api.check_box.all")}
										</ElCheckbox>
										<span class="mr-auto ml-4">
											{proxy?.$t("basic_api.title_label.current")}
											{data.ckInfo.appName}
										</span>
									</>
								) : (
									""
								)}
								<div class="flex">
									<ElInput class="mr-2" v-model={data.searchVal} clearable placeholder={proxy?.$t("basic_api.input.placeholder")}>
										{{
											append: () => {
												return (
													<el-button
														onClick={() => {
															handleFun("filter");
														}}
													>
														<span class="iconfont iconsearch" />
													</el-button>
												);
											}
										}}
									</ElInput>
									<ElButton
										type="primary"
										disabled={data.ckInfo.appId == undefined}
										onClick={() => {
											handleFun("save");
										}}
									>
										{proxy?.$t("basic_api.btn.save")}
									</ElButton>
								</div>
							</div>
							<ProTable
								ref={tableRef}
								columns={data.columnApi}
								requestApi={getTree}
								dataCallback={getApiTree}
								pagination={false}
								size="small"
								spanShow={data.spanShow}
								border={true}
								toolButton={false}
								stripe={false}
								highlightRow={false}
								class="table-filter"
							>
								{{
									CName: (scoped: any) => {
										return h(
											data.spanShow ? (
												<ElCheckbox
													modelValue={data.ckList.includes(scoped.row.FId)}
													onChange={(el: any) => {
														ckChange(scoped.row, el, 2);
													}}
												>
													{scoped.row.CName}
												</ElCheckbox>
											) : (
												<span>{scoped.row.CName}</span>
											)
										);
									},
									FName: (scoped: any) => {
										return h(
											<>
												{scoped.row.FName ? (
													<ElCheckbox
														modelValue={data.ckList.includes(scoped.row.path || scoped.row.FId)}
														onChange={(el: any) => {
															ckChange(scoped.row, el, 3);
														}}
													>
														{scoped.row.FName}
														<span class="ml-2 color-p">{scoped.row.path}</span>
													</ElCheckbox>
												) : (
													""
												)}
											</>
										);
									}
								}}
							</ProTable>
						</div>
					</div>
					<Form
						ref={refForm}
						getList={() => {
							proTable.value?.resetEstend();
						}}
					/>
					<DialogBox
						v-model:visible={data.showToken}
						title="Token"
						width="600px"
						footerLabel={[proxy?.$t("basic_api.footerlabel.cancel")]}
					>
						{data.tokenInfo}
						<i
							class="iconfont iconcopy ml-1 cursor-pointer"
							title={proxy?.$t("basic_api.dialog_title.copy")}
							onClick={() => {
								handleFun("copy");
							}}
						></i>
					</DialogBox>
				</div>
			);
		};
	}
});
export default API;
